package com.COMP3111H.project;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Search extends Activity {
	final int HELP = 0;
	// ProgressDialog dialog;

	ProgressThread progThread;
	final int SPINNER = 0;
	ProgressDialog progDialog;
	Button menu;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search);

		Button go = (Button) findViewById(R.id.Go);
		final EditText editText = (EditText) findViewById(R.id.Search_Key);

		editText.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// If the event is a key-down event on the "enter" button
				if ((event.getAction() == KeyEvent.ACTION_DOWN)
						&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
					String input = editText.getText().toString();
					if (NetworkUtility.inputCheck(input)) {
						// For testing purpose
						// Switch to SearchResult when the input is null
						// otherwise switch to SearchNotFound

						switchActivity(input);
					} else {
						Toast.makeText(
								Search.this,
								"There are special characters that are not allowed in your request",
								Toast.LENGTH_SHORT).show();
					}
					return true;
				}
				return false;
			}
		});

		go.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				String input = editText.getText().toString();
				// For testing purpose
				// Switch to SearchResult when the input is null
				// otherwise switch to SearchNotFound
				if (!NetworkUtility.inputCheck(input))
					Toast.makeText(
							Search.this,
							"There are special characters that are not allowed in your request",
							Toast.LENGTH_SHORT).show();
				else if (input.matches(""))
					Toast.makeText(Search.this,
							"Please input the search keywords",
							Toast.LENGTH_SHORT).show();
				else {
					switchActivity(input);
				}
			}
		});

		Button scan = (Button) findViewById(R.id.Scan);
		scan.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent myIntent = new Intent(Search.this, CaptureActivity.class);
				startActivity(myIntent);
			}
		});
		menu = (Button) findViewById(R.id.search_menu);
	}
	
	@Override
    protected void onResume() {
		super.onResume();
		if (LoginUtility.checkLoginStatus(this)) {
			menu.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					 String[] choices={"Home","View My Profile","Help","Cancel"};  
					             AlertDialog dialog = new AlertDialog.Builder(Search.this)  
					                     // .setIcon(android.R.drawable.btn_star)  
					                      .setTitle("Menu")  
					                      .setItems(choices, onselect_logged).create();  
					             dialog.show();  
				}
			});
		}
		else{
			menu.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					 String[] choices={"Home","Help","Cancel"};  
					             AlertDialog dialog = new AlertDialog.Builder(Search.this)  
					                     // .setIcon(android.R.drawable.btn_star)  
					                      .setTitle("Menu")  
					                      .setItems(choices, onselect_not_logged).create();  
					             dialog.show();  
				}
			});
		}
	}

	OnClickListener onselect_logged = new OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			// TODO Auto-generated method stub
			Intent myIntent;
			switch (which) {
			case 0:
				myIntent = new Intent(Search.this, Home.class);
				startActivity(myIntent);
				break;
			case 1:
				myIntent = new Intent(Search.this, My_Profile.class);
				startActivity(myIntent);
				break;
			case 2:
				myIntent = new Intent(Search.this, Help.class);
				startActivity(myIntent);
				break;
			case 3:
				dialog.dismiss();
				break;
			}
		}
	};
	
	OnClickListener onselect_not_logged = new OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			// TODO Auto-generated method stub
			Intent myIntent;
			switch (which) {
			case 0:
				myIntent = new Intent(Search.this, Home.class);
				startActivity(myIntent);
				break;
			case 1:
				myIntent = new Intent(Search.this, Help.class);
				startActivity(myIntent);
				break;
			case 2:
				dialog.dismiss();
				break;
			}
		}
	};

	private void switchActivity(String input) {
		// TODO
		if (NetworkUtility.isOnline(this)) {
			showDialog(SPINNER);
			progThread = new ProgressThread(handler, input);
			progThread.start();
		} else
			Toast.makeText(Search.this, "Network connection is not available",
					Toast.LENGTH_SHORT).show();
	}

	// Method to create a progress bar dialog of either spinner or horizontal
	// type
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case 0: // Spinner
			progDialog = new ProgressDialog(this);
			progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progDialog.setMessage("Searching...");

			return progDialog;
		default:
			return null;
		}
	}

	// Handler on the main (UI) thread that will receive messages from the
	// second thread and update the progress.

	final Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			// Get the current value of the variable total from the message data
			// and update the progress bar.
			int length = msg.getData().getInt("returnedLength");
			String returnedData = msg.getData().getString("returnedData");
			removeDialog(SPINNER);		
			
			if (returnedData == "error") {
				Toast.makeText(Search.this,
						"Network Error.Please check your network connection",
						Toast.LENGTH_SHORT).show();
			} 
			else {
				String returnedException = msg.getData().getString("returnedException");
				if (returnedException == "ExceptionCaught") {
					Toast.makeText(Search.this, "An error occured.",Toast.LENGTH_SHORT).show();
				} 
				else {
					if (length == 0) {
						Intent myIntent = new Intent(Search.this, SearchNotFound.class);
						startActivity(myIntent);
					} 
					else {
						Intent myIntent = new Intent(Search.this,SearchResult.class);
						myIntent.putExtra("data", returnedData);
						startActivity(myIntent);
					}
				}
			}

		}
	};

	private class ProgressThread extends Thread {
		// Class constants defining state of the thread
		Handler mHandler;
		String input;

		ProgressThread(Handler h, String s) {
			mHandler = h;
			input = s;
		}

		@Override
		public void run() {
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("input", input));
			
			String returnedData = NetworkUtility
					.sendHTTP(params,
							"http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/inputsearch.jsp");
			Log.v("Bookwarm", input);
			Log.v("Bookwarm", returnedData);
			
			Message msg = mHandler.obtainMessage();
			
			if (returnedData == "error") {
				Bundle b = new Bundle();
				b.putString("returnedData", returnedData);
				msg.setData(b);
				mHandler.sendMessage(msg);

			} else {
				try {
					JSONArray jArray = new JSONArray(returnedData);
					int length = jArray.length();
					Log.v("Bookwarm", String.valueOf(length));

					Bundle b = new Bundle();
					b.putInt("returnedLength", length);
					b.putString("returnedData", returnedData);
					msg.setData(b);
					mHandler.sendMessage(msg);

				} catch (JSONException e) {
					Bundle b = new Bundle();
					b.putString("returnedException","ExceptionCaught");
					msg.setData(b);
					mHandler.sendMessage(msg);
				}
			}
		}

		// Set current state of thread (use state=ProgressThread.DONE to stop
		// thread)

	}
}
